<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"
             class="main-search">
      <el-form-item label="用户账号" prop="userName">
        <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户账号"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="推送时间">
        <el-date-picker
            v-model="dateRange"
            style="width: 480px"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleConfig"
            v-hasPermi="['system:loginRecord:config']"
        >配置
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="loginRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="访问ID" align="center" prop="id" v-if="true"/>-->
      <!--      <el-table-column label="用户ID" align="center" prop="userId" />-->
      <el-table-column label="用户账号" align="center" prop="userName"/>
      <el-table-column label="登录时间" align="center" prop="loginTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.loginTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="登录IP地址" align="center" prop="ipaddr"/>
      <el-table-column label="登录地点" align="center" prop="loginLocation"/>
      <el-table-column label="浏览器类型" align="center" prop="browser"/>
      <el-table-column label="操作系统" align="center" prop="os"/>
      <!--      <el-table-column label="时间规则" align="center" prop="timeRule"/>-->
      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button-->
      <!--            size="mini"-->
      <!--            type="text"-->
      <!--            icon="el-icon-edit"-->
      <!--            @click="handleUpdate(scope.row)"-->
      <!--            v-hasPermi="['system:loginRecord:edit']"-->
      <!--          >修改</el-button>-->
      <!--          <el-button-->
      <!--            size="mini"-->
      <!--            type="text"-->
      <!--            icon="el-icon-delete"-->
      <!--            @click="handleDelete(scope.row)"-->
      <!--            v-hasPermi="['system:loginRecord:remove']"-->
      <!--          >删除</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改系统异常时间登录记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID"/>
        </el-form-item>
        <el-form-item label="用户账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户账号"/>
        </el-form-item>
        <el-form-item label="登录IP地址" prop="ipaddr">
          <el-input v-model="form.ipaddr" placeholder="请输入登录IP地址"/>
        </el-form-item>
        <el-form-item label="登录地点" prop="loginLocation">
          <el-input v-model="form.loginLocation" placeholder="请输入登录地点"/>
        </el-form-item>
        <el-form-item label="浏览器类型" prop="browser">
          <el-input v-model="form.browser" placeholder="请输入浏览器类型"/>
        </el-form-item>
        <el-form-item label="操作系统" prop="os">
          <el-input v-model="form.os" placeholder="请输入操作系统"/>
        </el-form-item>
        <el-form-item label="提示消息" prop="msg">
          <el-input v-model="form.msg" placeholder="请输入提示消息"/>
        </el-form-item>
        <el-form-item label="登录时间" prop="loginTime">
          <el-date-picker clearable
                          v-model="form.loginTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择登录时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 异常登录时间配置 -->
    <el-dialog title="工作时间配置" :visible.sync="configOpen" width="800px" append-to-body>
      <el-form ref="configForm" :model="configForm" label-width="80px">
        <el-form-item label="周期：">
          <el-checkbox-group v-model="configForm.info.weekConfig">
            <el-checkbox v-for="week in this.weekList" :label="week" :key="week" :name="week"></el-checkbox>
          </el-checkbox-group>
          <!--          <el-input v-model="configForm.bz" placeholder="请填写记录信息"/>-->
        </el-form-item>
        <el-form-item label="时间：">
          <el-time-select
              placeholder="起始时间"
              v-model="configForm.info.startTime"
              :picker-options="{
            start: '08:00',
            step: '00:30',
            end: '22:00'
          }">
          </el-time-select>
          至
          <el-time-select
              placeholder="结束时间"
              v-model="configForm.info.endTime"
              :picker-options="{
            start: '08:00',
            step: '00:30',
            end: '22:00',
            minTime: configForm.info.startTime
          }">
          </el-time-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitConfig">确 定</el-button>
        <el-button @click="configOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addLoginRecord,
  delLoginRecord,
  getLoginRecord,
  listLoginRecord,
  updateLoginRecord
} from "@/api/system/loginRecord/loginRecord";
import {noListConfig, saveConfig} from "@/api/system/loginRecord/config";

export default {
  name: "LoginRecord",
  data() {
    return {
      weekList: [
        '周一',
        '周二',
        '周三',
        '周四',
        '周五',
        '周六',
        '周日',
      ],
      configOpen: false,
      configForm: {
        type: 'login_time',
        info: {
          weekConfig: [],
          startTime: '',
          endTime: ''
        }
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 系统异常时间登录记录表格数据
      loginRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,
        userName: undefined,
        ipaddr: undefined,
        loginLocation: undefined,
        browser: undefined,
        os: undefined,
        status: undefined,
        msg: undefined,
        loginTime: undefined,
        timeRule: undefined,
        parentId: 0
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          {required: true, message: "访问ID不能为空", trigger: "blur"}
        ],
        userId: [
          {required: true, message: "用户ID不能为空", trigger: "blur"}
        ],
        userName: [
          {required: true, message: "用户账号不能为空", trigger: "blur"}
        ],
        ipaddr: [
          {required: true, message: "登录IP地址不能为空", trigger: "blur"}
        ],
        loginLocation: [
          {required: true, message: "登录地点不能为空", trigger: "blur"}
        ],
        browser: [
          {required: true, message: "浏览器类型不能为空", trigger: "blur"}
        ],
        os: [
          {required: true, message: "操作系统不能为空", trigger: "blur"}
        ],
        status: [
          {required: true, message: "登录状态不能为空", trigger: "change"}
        ],
        msg: [
          {required: true, message: "提示消息不能为空", trigger: "blur"}
        ],
        loginTime: [
          {required: true, message: "登录时间不能为空", trigger: "blur"}
        ],
        timeRule: [
          {required: true, message: "时间规则不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    submitConfig() {
      this.$refs["configForm"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          const data = {
            ...this.configForm,
            info: JSON.stringify(this.configForm.info)
          }
          saveConfig(data).then(res => {
            this.$modal.msgSuccess("配置成功");
            this.configOpen = false;
          }).finally(() => {
            this.buttonLoading = false;
          })
        }
      });
    },

    // 配置信息
    handleConfig() {
      // 查询配置信息--
      const param = {
        type: 'login_time'
      }
      this.configForm = {
        type: 'login_time',
        info: {
          weekConfig: [],
          startTime: '',
          endTime: ''
        }
      };
      noListConfig(param).then(res => {
        if (res.code == 200) {
          const list = res.data;
          if (list.length > 0) {
            this.configForm = list[0];
            this.configForm.info = JSON.parse(this.configForm.info, this.configForm.info);
          }
        }
      });
      this.configOpen = true;
    },
    /** 查询系统异常时间登录记录列表 */
    getList() {
      this.loading = true;
      listLoginRecord(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.loginRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        userId: undefined,
        userName: undefined,
        ipaddr: undefined,
        loginLocation: undefined,
        browser: undefined,
        os: undefined,
        status: undefined,
        msg: undefined,
        loginTime: undefined,
        timeRule: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加系统异常时间登录记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getLoginRecord(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改系统异常时间登录记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateLoginRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addLoginRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除系统异常时间登录记录编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delLoginRecord(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/loginRecord/export', {
        ...this.queryParams
      }, `loginRecord_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
